﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Util;
using Coldairarrow.Util.Helper;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class Interface_BaseBusiness
    {
        //接口名称
        public bool IsLogQuery { get; set; } = true;

        //接口名称
        public string InterfaceName { get; set; }
        //接口配置
        public List<Base_InterfaceOption> interfaceOption { get; set; }
        //表格映射
        public Dictionary<string, string> tableField { get; set; } = new Dictionary<string, string>();
        //索引字段
        public List<string> indexFields { get; set; } = new List<string>();

        public List<ComparerKeys> Keys { get; set; } = new List<ComparerKeys>();

        //查询总条数
        public int NoQueryNum { get; set; }
        //查询是否成功状态=0异常，>0正常
        public int State { get; set; } = 3;
        public SqlServerHelper SqlDb;
        public OracleHelper OracleDb;
        public string ConString;
        public Interface_BaseBusiness()
        {

        }


        // 执行请求前事件
        public delegate void BeforeNoQueryEventHandler(object sender, NoQueryEventArgs noQueryEventArgs);
        public event BeforeNoQueryEventHandler BeforeNoQueryEvent;
        protected virtual void BeforeNoQuery(NoQueryEventArgs noQueryEventArgs)
        {
            BeforeNoQueryEventHandler handler = BeforeNoQueryEvent;
            handler?.Invoke(this, noQueryEventArgs);
        }

        // 执行请求中事件
        public delegate void OnNoQueryEventHandler(object sender, NoQueryEventArgs noQueryEventArgs);
        public event OnNoQueryEventHandler OnNoQueryEvent;
        protected virtual void OnNoQuery(NoQueryEventArgs noQueryEventArgs)
        {
            OnNoQueryEventHandler handler = OnNoQueryEvent;
            handler?.Invoke(this, noQueryEventArgs);
        }

        // 执行请求后事件
        public delegate void AfterNoQueryEventHandler(object sender, NoQueryEventArgs noQueryEventArgs);
        public event AfterNoQueryEventHandler AfterNoQueryEvent;
        protected virtual void AfterNoQuery(NoQueryEventArgs noQueryEventArgs)
        {
            AfterNoQueryEventHandler handler = AfterNoQueryEvent;
            handler?.Invoke(this, noQueryEventArgs);
        }
        /// <summary>
        /// 执行非查询的API操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="datas"></param>
        /// <param name="APIOption"></param>
        /// <param name="db"></param>
        public async Task ExecuteNoQuery<T>(List<T> datas, Base_InterfaceOption APIOption, SqlServerHelper db)
        {

            if (datas.Count > 0)
            {

                db._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                //获取所有的参数字段信息
                List<Base_InterfaceOptionEntry> interfaceEntry = db.GetListBySql<Base_InterfaceOptionEntry>(@$"SELECT  * FROM  Base_InterfaceOptionEntry(NOLOCK) WHERE OptionId='{APIOption.Id}' ");
                //获取最高层级的父项
                List<Base_InterfaceOptionEntry> parentNode = interfaceEntry.Where(i => i.ParentId.IsNullOrEmpty()).ToList();

                HttpClient client = new HttpClient();
                string data = "";
                string jsonResult = "";
                JObject result;
                //bool success;
                //执行超过次数不在请求
                int requestCountOut = 3;
                //执行非查询操作成功数量
                int successCount = 0;
                NoQueryEventArgs eventArgs = new NoQueryEventArgs();
                await Task.Run(() =>
                {
                    int c = requestCountOut;
                    State = requestCountOut;
                    datas.ForEach(d =>
                    {
                        if (c == 0) return;
                        //执行请求前事件
                        BeforeNoQuery(eventArgs);
                        NoQueryNum++;
                        if (NoQueryNum == datas.Count)
                        {
                            NoQueryNum = 0;
                        }
                        eventArgs.Success = false;

                        while (!eventArgs.Success)
                        {

                            try
                            {

                                data = GetJsonData(interfaceEntry, parentNode, d);
                                client.Content = data;
                                client.Url = APIOption.TargetUrl;
                                jsonResult = client.Request();
                                result = JObject.Parse(jsonResult);
                                eventArgs.Result = result;
                                //执行请求中事件
                                OnNoQuery(eventArgs);

                                if (!eventArgs.Success)
                                {
                                    AddLog(db, jsonResult, InterfaceName, APIOption.OperateType, $"{data}");
                                    Thread.Sleep(2000);
                                    c--;
                                    //超过次数退出循环不在请求
                                    if (c == 0)
                                    {
                                        State = c;
                                        break;
                                    }
                                }
                                else
                                {
                                    c = requestCountOut;
                                    successCount++;
                                }


                            }
                            catch (Exception ex)
                            {
                                AddLog(db, jsonResult + "----" + ex.Message, InterfaceName, APIOption.OperateType, $"{data}");
                                c--;
                                if (c == 0)
                                {
                                    State = c;
                                    break;
                                }
                                Thread.Sleep(2000);
                            }
                        }

                        //执行请求后事件
                        AfterNoQuery(eventArgs);

                    });
                    if (c > 0)
                    {
                        AddLog(db, $"执行完成，执行总数量{datas.Count},成功总数{successCount},异常总数{datas.Count - successCount}", InterfaceName, APIOption.OperateType, "");
                    }
                    else
                    {
                        AddLog(db, $"异常推出，执行总数量{successCount},未执行总数{datas.Count - successCount}", InterfaceName, APIOption.OperateType, "");
                    }

                });
            }

        }

        // 查询前事件
        public delegate void BeforeQueryEventHandler(object sender, QueryEventArgs queryEventArgs);
        public event BeforeQueryEventHandler BeforeQueryEvent;
        protected virtual void BeforeQuery(QueryEventArgs queryEventArgs)
        {
            BeforeQueryEventHandler handler = BeforeQueryEvent;
            handler?.Invoke(this, queryEventArgs);
        }

        // 查询中事件
        public delegate void OnQueryEventHandler(object sender, QueryEventArgs queryEventArgs);
        public event OnQueryEventHandler OnQueryEvent;
        protected virtual void OnQuery(QueryEventArgs queryEventArgs)
        {
            OnQueryEventHandler handler = OnQueryEvent;
            handler?.Invoke(this, queryEventArgs);
        }

        // 查询后事件
        public delegate void AfterQueryEventHandler(object sender, QueryEventArgs queryEventArgs);
        public event AfterQueryEventHandler AfterQueryEvent;
        protected virtual void AfterQuery(QueryEventArgs queryEventArgs)
        {
            AfterQueryEventHandler handler = AfterQueryEvent;
            handler?.Invoke(this, queryEventArgs);
        }
        /// <summary>
        /// 执行查询的API操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="APIOption"></param>
        /// <param name="db"></param>
        /// <param name="tableFields">源数据与目标数据的映射关系</param>
        /// <returns></returns>
        public async Task<List<T>> QueryAsync<T>(Base_InterfaceOption APIOption, Dictionary<string, string> tableFields, SqlServerHelper db)
        {
            db._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            //获取所有的参数字段信息
            List<Base_InterfaceOptionEntry> interfaceEntry = db.GetListBySql<Base_InterfaceOptionEntry>(@$"SELECT  * FROM  Base_InterfaceOptionEntry(NOLOCK) WHERE OptionId='{APIOption.Id}' ");
            //获取最高层级的父项
            List<Base_InterfaceOptionEntry> parentNode = interfaceEntry.Where(i => i.ParentId.IsNullOrEmpty()).ToList();
            HttpClient client = new HttpClient();
            client.Url = APIOption.TargetUrl;
            //请求的json字符串数据
            string data = "";
            //请求后返回的结果json字符串
            string jsonResult = "";
            //执行超过次数不在请求
            int countOut = 3;
            //转换后的所有数据
            List<T> rows_T = new List<T>();
            //请求的事件参数
            QueryEventArgs queryEventArgs = new QueryEventArgs();
            queryEventArgs.Page = new QueryPage();
            queryEventArgs.Result = null;
            queryEventArgs.Success = false;
            queryEventArgs.Rows = new List<JToken>();
            queryEventArgs.HttpClient = client;
            queryEventArgs.APINodes = interfaceEntry;
            await Task.Run(() =>
            {
                int c = countOut;
                State = countOut;
                //循环将所有数据获取
                while (!queryEventArgs.Page.Complete)
                {
                    try
                    {
                        BeforeQuery(queryEventArgs);
                        data = GetJsonData(interfaceEntry, parentNode, queryEventArgs.Page);
                        client.Content = data;
                        //发起http请求
                        jsonResult = client.Request();
                        queryEventArgs.Result = JObject.Parse(jsonResult);

                        //执行查询事件
                        OnQuery(queryEventArgs);
                        //查询完成退出循环
                        if (queryEventArgs.Page.Complete == true) break;

                        //查询是否成功
                        if (queryEventArgs.Success)
                        {
                            queryEventArgs.Page.PageIndex++;
                            c = countOut;
                        }
                        else
                        {
                            c--;
                            AddLog(db, jsonResult, InterfaceName, APIOption.OperateType, $"{data}");
                            Thread.Sleep(2000);
                            //超过次数退出循环不在请求
                            if (c == 0)
                            {
                                State = c;
                                queryEventArgs.Rows.Clear();
                                break;
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        c--;
                        if (c == 0)
                        {
                            State = c;
                            queryEventArgs.Rows.Clear();
                            break;
                        }
                        AddLog(db, jsonResult + "----" + ex.Message, InterfaceName, APIOption.OperateType, $"{data}");
                        Thread.Sleep(2000);
                    }

                }

                //查询后事件
                AfterQuery(queryEventArgs);
                //将获取的json所有行转换成对应的对象列表
                if (queryEventArgs.Rows.Count > 0)
                {
                    foreach (JToken row in queryEventArgs.Rows)
                    {
                        T t = Activator.CreateInstance<T>();
                        foreach (var item in Keys)
                        {
                            var propertyInfo = typeof(T).GetProperty(item.Field);
                            //if (t.ContainsProperty(item.Field))
                            //{
                            if (!propertyInfo.IsNullOrEmpty())
                            {
                                object Value;
                                if (row[item.TField].IsNullOrEmpty())
                                {
                                    Value = null;
                                }
                                else
                                {
                                    if (propertyInfo.PropertyType.Name == "String")
                                    {
                                        Value = row[item.TField].ToString();
                                    }
                                    else
                                    {
                                        var v = row[item.TField].ToString();
                                        Value = v.ToObject(propertyInfo.PropertyType);
                                    }

                                }
                                t.SetPropertyValue(item.Field, Value);
                            }
                        }

                        rows_T.Add(t);
                    }
                }

                if (c > 0)
                {
                    if (IsLogQuery) AddLog(db, $"查询操作成功，查询总条数{rows_T.Count}", InterfaceName, APIOption.OperateType, "");
                }
                else
                {
                    AddLog(db, $"异常推出，查询总条数{rows_T.Count}", InterfaceName, APIOption.OperateType, "");
                }

                queryEventArgs.Rows.Clear();

            });

            return rows_T;
        }




        /// <summary>
        /// 执行查询的API操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="APIOption"></param>
        /// <param name="db"></param>
        /// <param name="tableFields">源数据与目标数据的映射关系</param>
        /// <returns></returns>
        public List<T> Query<T>(Base_InterfaceOption APIOption, Dictionary<string, string> tableFields, SqlServerHelper db)
        {
            db._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            //获取所有的参数字段信息
            List<Base_InterfaceOptionEntry> interfaceEntry = db.GetListBySql<Base_InterfaceOptionEntry>(@$"SELECT  * FROM  Base_InterfaceOptionEntry(NOLOCK) WHERE OptionId='{APIOption.Id}' ");
            //获取最高层级的父项
            List<Base_InterfaceOptionEntry> parentNode = interfaceEntry.Where(i => i.ParentId.IsNullOrEmpty()).ToList();
            HttpClient client = new HttpClient();
            client.Url = APIOption.TargetUrl;
            //请求的json字符串数据
            string data = "";
            //请求后返回的结果json字符串
            string jsonResult = "";
            //执行超过次数不在请求
            int countOut = 3;
            //转换后的所有数据
            List<T> rows_T = new List<T>();
            //请求的事件参数
            QueryEventArgs queryEventArgs = new QueryEventArgs();
            queryEventArgs.Page = new QueryPage();
            queryEventArgs.Result = null;
            queryEventArgs.Success = false;
            queryEventArgs.Rows = new List<JToken>();
            queryEventArgs.HttpClient = client;


            int c = countOut;
            State = countOut;
            //循环将所有数据获取
            while (!queryEventArgs.Page.Complete)
            {
                try
                {
                    BeforeQuery(queryEventArgs);
                    data = GetJsonData(interfaceEntry, parentNode, queryEventArgs.Page);
                    client.Content = data;
                    //发起http请求
                    jsonResult = client.Request();
                    queryEventArgs.Result = JObject.Parse(jsonResult);

                    //执行查询事件
                    OnQuery(queryEventArgs);
                    //查询完成退出循环
                    if (queryEventArgs.Page.Complete == true) break;

                    //查询是否成功
                    if (!queryEventArgs.Success)
                    {
                        AddLog(db, jsonResult, InterfaceName, APIOption.OperateType, $"{data}");
                        Thread.Sleep(2000);
                        c--;
                        //超过次数退出循环不在请求
                        if (c == 0)
                        {
                            State = c;
                            queryEventArgs.Rows.Clear();
                            break;
                        }
                    }
                    else
                    {
                        queryEventArgs.Page.PageIndex++;
                        c = countOut;
                    }

                }
                catch (Exception ex)
                {
                    c--;
                    if (c == 0)
                    {
                        State = c;
                        queryEventArgs.Rows.Clear();
                        break;
                    }
                    AddLog(db, jsonResult + "----" + ex.Message, InterfaceName, APIOption.OperateType, $"{data}");
                    Thread.Sleep(2000);
                }

            }

            //查询后事件
            AfterQuery(queryEventArgs);
            //将获取的json所有行转换成对应的对象列表
            if (queryEventArgs.Rows.Count > 0)
            {
                foreach (JToken row in queryEventArgs.Rows)
                {
                    T t = Activator.CreateInstance<T>();
                    foreach (var item in Keys)
                    {
                        var propertyInfo = typeof(T).GetProperty(item.Field);
                        //if (t.ContainsProperty(item.Field))
                        //{
                        if (!propertyInfo.IsNullOrEmpty())
                        {
                            object Value;
                            if (row[item.TField].IsNullOrEmpty())
                            {
                                Value = null;
                            }
                            else
                            {
                                if (propertyInfo.PropertyType.Name == "String")
                                {
                                    Value = row[item.TField].ToString();
                                }
                                else
                                {
                                    var v = row[item.TField].ToString();
                                    Value = v.ToObject(propertyInfo.PropertyType);
                                }

                            }
                            t.SetPropertyValue(item.Field, Value);
                        }
                    }

                    rows_T.Add(t);
                }
            }

            if (c > 0)
            {
                if (IsLogQuery) AddLog(db, $"查询操作成功，查询总条数{rows_T.Count}", InterfaceName, APIOption.OperateType, "");
            }
            else
            {
                AddLog(db, $"异常推出，查询总条数{rows_T.Count}", InterfaceName, APIOption.OperateType, "");
            }

            queryEventArgs.Rows.Clear();


            return rows_T;
        }




        /// <summary>
        /// 根据接口配置获取请求的DATA
        /// </summary>
        /// <param name="interfaceEntry"></param>
        /// <param name="parentNode">父节点列表</param>
        /// <param name="sourceData">源数据</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string GetJsonData(List<Base_InterfaceOptionEntry> interfaceEntry, List<Base_InterfaceOptionEntry> parentNode, object sourceData = null)
        {

            StringBuilder data = new StringBuilder();
            int index = parentNode.Count;
            string last = "";
            try
            {
                parentNode.ForEach(i =>
                {
                    index--;
                    StringBuilder node = new StringBuilder();
                    string fieldName = "";
                    string fieldValue = "";
                    string parentId = i.Id;
                    switch (i.TargetFieldType)
                    {
                        //字段类型为字符串json拼接
                        case "String":
                            //获取字段名称
                            fieldName = i.TargetField.IsNullOrEmpty() ? "" : $"\"{i.TargetField}\":";
                            //获取字段值
                            if (i.MapType == "V")
                            {
                                fieldValue = i.SourceField.IsNullOrEmpty() ? "\"\"" : $"\"{i.SourceField}\"";
                            }
                            else if (i.MapType == "D")
                            {
                                try
                                {
                                    var o = sourceData.GetPropertyValue(i.SourceField);
                                    fieldValue = o.IsNullOrEmpty() ? "\"\"" : $"\"{o.ToString().Escape(@"\", "\"")}\"";

                                }
                                catch (Exception ex)
                                {
                                    throw new Exception($"{DateTime.Now.ToString("yyyy:MM:dd HH:MM")}:节点名称{fieldName},无法找到对应的String类型数据字段{i.SourceField}，数据类名称{sourceData.GetType().Name}.");
                                }
                            }
                            //拼接json的字段名称
                            node.Append(fieldName);
                            //拼接json的字段的值
                            node.Append(fieldValue);
                            //如果是最后一个子项则不需要带,结尾
                            last = index != 0 ? "," : "";
                            node.Append(last);
                            data.Append(node.ToString());
                            break;


                        //字段类型为字数值json拼接
                        case "Int":
                            //获取字段名称
                            fieldName = i.TargetField.IsNullOrEmpty() ? "" : $"\"{i.TargetField}\":";
                            //获取字段值
                            if (i.MapType == "V")
                            {
                                fieldValue = i.SourceField.IsNullOrEmpty() ? "0" : $"{i.SourceField}";
                            }
                            else if (i.MapType == "D")
                            {
                                try
                                {
                                    var o = sourceData.GetPropertyValue(i.SourceField);
                                    fieldValue = o.IsNullOrEmpty() ? "0" : $"{o.ToString()}";
                                }
                                catch (Exception ex)
                                {
                                    throw new Exception($"{DateTime.Now.ToString("yyyy:MM:dd HH:MM")}:节点名称{fieldName},无法找到对应的Int类型数据字段{i.SourceField}，数据类名称{sourceData.GetType().Name}.");
                                }
                            }
                            //拼接json的字段名称
                            node.Append(fieldName);
                            //拼接json的字段的值
                            node.Append(fieldValue);
                            //如果是最后一个子项则不需要带,结尾
                            last = index != 0 ? "," : "";
                            node.Append(last);
                            data.Append(node.ToString());
                            break;


                        //字段类型为字布尔json拼接
                        case "Bool":
                            //获取字段名称
                            fieldName = i.TargetField.IsNullOrEmpty() ? "" : $"\"{i.TargetField}\":";
                            //获取字段值
                            if (i.MapType == "V")
                            {
                                fieldValue = i.SourceField.IsNullOrEmpty() ? "FALSE" : $"{i.SourceField}";
                            }
                            else if (i.MapType == "D")
                            {
                                try
                                {
                                    var o = sourceData.GetPropertyValue(i.SourceField);
                                    fieldValue = o.IsNullOrEmpty() ? "FALSE" : $"{o.ToString()}";
                                }
                                catch (Exception ex)
                                {
                                    throw new Exception($"{DateTime.Now.ToString("yyyy:MM:dd HH:MM")}:节点名称{fieldName},无法找到对应的bool类型数据字段{i.SourceField}，数据类名称{sourceData.GetType().Name}.");
                                }
                            }
                            //拼接json的字段名称
                            node.Append(fieldName);
                            //拼接json的字段的值
                            node.Append(fieldValue);
                            //如果是最后一个子项则不需要带,结尾
                            last = index != 0 ? "," : "";
                            node.Append(last);
                            data.Append(node.ToString());
                            break;

                        //字段类型为对象json拼接
                        case "Object":
                            //获取字段名称
                            fieldName = i.TargetField.IsNullOrEmpty() ? "" : $"\"{i.TargetField}\":";
                            //获取字段值
                            {
                                //获取子项
                                List<Base_InterfaceOptionEntry> childs = interfaceEntry.Where(e => e.ParentId == parentId).ToList();

                                //获取子项的数据,如果为D,子项的数据使方法的sourceData，否则使用参数自身的设置值
                                if (i.MapType == "D")
                                {
                                    object childData = new object();
                                    try
                                    {
                                        childData = i.SourceField.IsNullOrEmpty() ? sourceData : sourceData.GetPropertyValue(i.SourceField);
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception($"{DateTime.Now.ToString("yyyy:MM:dd HH:MM")}:节点名称{fieldName},无法找到对应的Object类型数据字段{i.SourceField}，数据类名称{sourceData.GetType().Name}.");
                                    }
                                    //如果子项大于0，则继续递归获取子项值
                                    if (childs.Count > 0)
                                    {
                                        fieldValue = GetJsonData(interfaceEntry, childs, childData);
                                    }
                                    else
                                    {
                                        fieldValue = " ";
                                    }
                                }
                                else if (i.MapType == "V")
                                {
                                    fieldValue = GetJsonData(interfaceEntry, childs, sourceData);
                                }
                            }
                            //拼接json的字段名称
                            node.Append(fieldName);
                            node.Append("{");
                            //拼接json的字段的值
                            node.Append(fieldValue);
                            //如果是最后一个子项则不需要带,结尾
                            last = index != 0 ? "}," : "}";
                            node.Append(last);
                            data.Append(node.ToString());
                            break;

                        //字段类型为数组json拼接
                        case "Array":
                            //获取字段名称
                            fieldName = i.TargetField.IsNullOrEmpty() ? "" : $"\"{i.TargetField}\":";
                            //获取字段值
                            {
                                //获取子项
                                List<Base_InterfaceOptionEntry> childs = interfaceEntry.Where(e => e.ParentId == parentId).ToList();
                                string temp = "";
                                //获取子项的数据,如果为D,子项的数据使方法的sourceData，否则使用参数自身的设置值
                                if (i.MapType == "D")
                                {
                                    List<object> childDatas = new List<object>();
                                    try
                                    {
                                        childDatas = i.SourceField.IsNullOrEmpty() ? sourceData.ObjToList() : sourceData.GetPropertyValue(i.SourceField).ObjToList();
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception($"{DateTime.Now.ToString("yyyy:MM:dd HH:MM")}:节点名称{fieldName},无法找到对应的Array类型数据{i.SourceField}，数据类名称{sourceData.GetType().Name}.");
                                    }
                                    //如果子项大于0，则继续递归获取子项值
                                    if (childs.Count > 0)
                                    {
                                        StringBuilder ArrayData = new StringBuilder();
                                        int count = childDatas.Count;
                                        //循环获取数组的每一项数据
                                        childDatas.ForEach(childData =>
                                        {
                                            count--;
                                            ArrayData.Append(GetJsonData(interfaceEntry, childs, childData));
                                            ArrayData.Append(count != 0 ? (",") : "");
                                        });
                                        fieldValue = ArrayData.ToString();
                                    }
                                    else
                                    {
                                        fieldValue = " ";
                                    }
                                }
                                else if (i.MapType == "V")
                                {
                                    fieldValue = GetJsonData(interfaceEntry, childs, sourceData);
                                }
                            }
                            //拼接json的字段名称
                            node.Append(fieldName);
                            node.Append("[");
                            //拼接json的字段的值
                            node.Append(fieldValue);
                            //如果是最后一个子项则不需要带,结尾
                            last = index != 0 ? "]," : "]";
                            node.Append(last);
                            data.Append(node.ToString());
                            break;
                    }
                });
            }
            catch (Exception ex)
            {

            }

            return data.ToString();
        }
        /// <summary>
        /// 添加接口日志
        /// </summary>
        /// <param name="logContent"></param>
        /// <param name="inerfaceName"></param>
        /// <param name="db"></param>
        /// <param name="inerfaceData"></param>
        /// <param name="logType"></param>
        public void AddLog(SqlServerHelper db, string logContent, string inerfaceName, string logType = " ", string inerfaceData = " ")
        {
            try
            {
                db._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                List<DbParameter> parameters = new List<DbParameter>();
                parameters.Add(SqlStringHelper.CreateParameter("@id", IdHelper.GetId()));
                parameters.Add(SqlStringHelper.CreateParameter("@createTime", DateTime.Now));
                parameters.Add(SqlStringHelper.CreateParameter("@creatorRealName", ""));
                parameters.Add(SqlStringHelper.CreateParameter("@creatorId", "Admin"));
                parameters.Add(SqlStringHelper.CreateParameter("@logType", logType));
                parameters.Add(SqlStringHelper.CreateParameter("@logContent", logContent));
                parameters.Add(SqlStringHelper.CreateParameter("@InterfaceName", inerfaceName));
                parameters.Add(SqlStringHelper.CreateParameter("@inerfaceData", inerfaceData));
                string sqlStr = @"INSERT INTO 
           Base_InterfaceLog(Id,CreateTime,CreatorRealName,CreatorId,LogType,LogContent,InterfaceName,InterfaceData) 
            VALUES(@id,@createTime,@creatorRealName,@creatorId,@logType,@logContent,@InterfaceName,@inerfaceData)";

                db.ExecuteSql(sqlStr, parameters);
            }
            catch (Exception ex)
            {


            }
        }


        /// <summary>
        /// 获取字段映射关系
        /// </summary>
        /// <param name="operateType">API接口的操作类型</param>
        /// <returns></returns>
        public Dictionary<string, string> GetMapField(string operateType)
        {
            Dictionary<string, string> d = new Dictionary<string, string>();
            try
            {
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);
                List<DbParameter> parameters = new List<DbParameter>();
                parameters.Add(SqlStringHelper.CreateParameter("@operateType", operateType));
                parameters.Add(SqlStringHelper.CreateParameter("@name", this.InterfaceName));
                string sqlStr = "select * from Base_InterfaceOption where Name=@name and OperateType=@operateType";
                string hId = SqlDb.GetListBySql<Base_InterfaceOption>(sqlStr, parameters)[0].Id;
                parameters.Clear();
                parameters.Add(SqlStringHelper.CreateParameter("@HId", hId));
                sqlStr = "select * from Base_InterfaceOptionEntryL where HId=@HId";
                SqlDb.GetListBySql<Base_InterfaceOptionEntryL>(sqlStr, parameters).ForEach(param => d.Add(param.TargetField, param.SourceField));

            }
            catch
            {


            }
            return d;
        }
        /// <summary>
        /// 获取Base_InterfaceOptionEntryL维护的逐渐
        /// </summary>
        /// <param name="operateType">API接口的操作类型</param>
        /// <returns></returns>
        public List<ComparerKeys> GetKeys(string operateType)
        {
            List<ComparerKeys> keys = new List<ComparerKeys>();
            try
            {
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);
                List<DbParameter> parameters = new List<DbParameter>();
                parameters.Add(SqlStringHelper.CreateParameter("@operateType", operateType));
                parameters.Add(SqlStringHelper.CreateParameter("@name", this.InterfaceName));
                string sqlStr = "select * from Base_InterfaceOption where Name=@name and OperateType=@operateType";
                string hId = SqlDb.GetListBySql<Base_InterfaceOption>(sqlStr, parameters)[0].Id;
                parameters.Clear();
                parameters.Add(SqlStringHelper.CreateParameter("@HId", hId));
                sqlStr = "select * from Base_InterfaceOptionEntryL where HId=@HId";
                SqlDb.GetListBySql<Base_InterfaceOptionEntryL>(sqlStr, parameters).ForEach(param => keys.Add(new ComparerKeys()
                {
                    Field = param.SourceField,
                    Type = param.IsKey,
                    TField = param.TargetField,
                    Note = param.Notes
                }));

            }
            catch
            {


            }
            return keys;
        }
        #region  废弃

        ///// <summary>
        ///// 根据筛选的索引获取数据
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="data">数据列表</param>
        ///// <param name="indexField">数据的索引字段</param>
        ///// <param name="indexValue">索引值列表，可以由多个索引通过特殊字符串拼接其他</param>
        ///// <param name="flag"></param>
        ///// <returns></returns>
        //public List<T> GetDataFormIndex<T>(List<T> data, List<string> indexFields, List<string> indexValues, string flag)
        //{
        //    ParameterExpression parameterExpression = Expression.Parameter(typeof(T), "x");
        //    Expression body = null;
        //    Expression value_e;
        //    PropertyInfo field;
        //    Expression field_e;
        //    MethodInfo equals;
        //    Expression method_e;
        //    string[] indexValue;
        //    Type type = typeof(T);
        //    IQueryable<T> queryable = data.AsQueryable();
        //    List<T> result = new List<T>();


        //    foreach (var item in indexValues)
        //    {
        //        //将字符串分割成单个
        //        indexValue = item.Split(flag);
        //        int index = 0;
        //        foreach (var item1 in indexValue)
        //        {
        //            if (!type.GetProperty(indexFields[index]).IsNullOrEmpty())
        //            {
        //                value_e = Expression.Constant(indexValue[index], typeof(string));
        //                field = type.GetProperty(indexFields[index]);
        //                field_e = Expression.Property(parameterExpression, field);
        //                equals = typeof(string).GetMethod("Equals", new Type[] { typeof(string) });
        //                method_e = Expression.Call(field_e, equals, value_e);
        //                //拼接二元表达式
        //                if (body.IsNullOrEmpty())
        //                {
        //                    //第一次不拼接二元式
        //                    body = method_e;
        //                }
        //                else
        //                {
        //                    //第二次拼接二元式
        //                    body = Expression.MakeBinary(ExpressionType.And, body, method_e);
        //                }
        //            }
        //            index++;
        //        }

        //        Expression<Func<T, bool>> expression = Expression.Lambda<Func<T, bool>>(body, parameterExpression);
        //        var s = queryable.Where(expression).First();

        //        result.Add(s);
        //        body = null;
        //    }

        //    //转换结构
        //    return result;
        //}
        ///// <summary>
        ///// 将列表s中对应的fields复制给t
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="s">源数据</param>
        ///// <param name="t">目标数据</param>
        ///// <param name="fields">复制字段</param>
        ///// <returns></returns>
        //public List<T> CopyFields<T>(List<T> s, List<T> t, List<string> indexFields, string setField)
        //{
        //    Type type = typeof(T);
        //    ParameterExpression parameterExpression = Expression.Parameter(typeof(T), "x");
        //    Expression body = null;
        //    Expression value_e;
        //    PropertyInfo field;
        //    Expression field_e;
        //    MethodInfo equals;
        //    Expression method_e;
        //    t.ForEach(t1 => {


        //        foreach (var f in indexFields)
        //        {
        //            value_e = Expression.Constant(t1.GetPropertyValue(f), typeof(string));
        //            field = type.GetProperty(f);
        //            field_e = Expression.Property(parameterExpression, field);
        //            equals = typeof(string).GetMethod("Equals", new Type[] { typeof(string) });
        //            method_e = Expression.Call(field_e, equals, value_e);
        //            //拼接二元表达式
        //            if (body.IsNullOrEmpty())
        //            {
        //                //第一次不拼接二元式
        //                body = method_e;
        //            }
        //            else
        //            {
        //                //第二次拼接二元式
        //                body = Expression.MakeBinary(ExpressionType.And, body, method_e);
        //            }
        //        }
        //        Expression<Func<T, bool>> expression = Expression.Lambda<Func<T, bool>>(body, parameterExpression);

        //        var temp = s.AsQueryable().Where(expression).First();
        //        t1.SetPropertyValue(setField, temp.GetPropertyValue(setField));
        //        body = null;
        //    });
        //    return t;
        //}
        #endregion
    }






}
